import { useEffect, useState } from 'react'
import { useRequest } from 'ahooks'
import useGetUserInfo from './useGetUserInfo'
import { useDispatch } from 'react-redux'
import { getUserInfoService } from '../services/user'
import { loginReducer } from '../store/userReducer'
function useLoadUserData() {
  const [waitingUserDate, setWaitingUserData] = useState(true)
  const dispatch = useDispatch()
  //ajax加载用户信息
  const { run } = useRequest(getUserInfoService, {
    manual: true,
    onSuccess(result) {
      const { username, nickname } = result
      //   存储到redux store
      dispatch(
        loginReducer({
          username,
          nickname,
        })
      )
    },
    onFinally() {
      setWaitingUserData(false)
    },
  })

  const { username } = useGetUserInfo()
  useEffect(() => {
    if (username) {
      setWaitingUserData(false) //如果redux store已经存在用户信息,就不用重新加载
      return
    }
    run() //如果redux store没有用户信息,则需要重新加载
  }, [username])
  // ajax加载用户信息之后,放在redux统一管理,不用返回

  return { waitingUserDate }
}

export default useLoadUserData
